import Vue from 'vue';
import XLSX from "xlsx";
import { Message } from 'element-ui';
Vue.prototype.$$getArrayName = function(value = '', array, prop = {
  value: 'code',
  label: 'dictName'
}){
  if(value === null) return '';
  if(typeof value === 'string'){
    value = value ? value.split(',') : [];
  }else if(typeof value === 'number'){
    value = [value];
  }
  return value.map(code => {
    let obj = array.find(o => o[prop['value']] === code);
    return obj ? obj[prop['label']] : ''
  }).toString();
}
//上传凭据的公共提示
Vue.prototype.$$commonNotice = function(str = '收款凭证'){
  Message.warning({
    message: `${str}一旦上传无法修改，请确保上传正确的${str}！`,
    duration: 0,
    showClose: true
  })
}
//太多了，写个这个
Vue.prototype.$$getCommonArrayName = function(value, array){
  return Vue.prototype.$$getArrayName(value, array, {
    label: 'label', value: 'value'
  })
}
Vue.prototype.$$validateCode = function(url, data, callback){
  this.$yAxios({
    url,
    data,
  }, info => {
    if(info) callback();
    else callback(new Error('编码重复'))
  }, e => {
    callback(new Error('校验编码失败，请联系管理员'))
  })
}
Vue.prototype.$$getFormatTime = function (timeNumber) {
  let date = new Date(timeNumber);
  let yy = date.getFullYear();
  let MM = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1);
  let dd = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  let hh = date.getHours();
  let mm = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
  let ss = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
  return yy + '-' + MM + '-' + dd + ' ' + hh + ':' + mm + ':' + ss;
}
//导出Excel
Vue.prototype.$$exportExcel = function({data, type='json', header, sheetName='Sheet1', fileName='SheetJS.xlsx'}){
  /*const data = [
    { S:1, h:2, e:3, e_1:4, t:5, J:6, id:7 },
    { S:2, h:3, e:4, e_1:5, t:6, J:7, id:8 }
  ];

  const data2 = [

    [ "id",    "name", "value" ],

    [    1, "sheetjs",    7262 ],

    [    2, "js-xlsx",    6969 ]

  ];
  const workSheet2= XLSX.utils.aoa_to_sheet(data2);

  const workSheet = XLSX.utils.json_to_sheet(data, {
    header: ['id', 'S', 'e', 'h', 'e_1', 't', 'J']
  });*/

  const workSheet= XLSX.utils.aoa_to_sheet(data);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, workSheet, sheetName);
  /* save to file */
  XLSX.writeFile(wb, fileName);
}

Vue.prototype.$$getUserInfo = function(){
  try{
    return JSON.parse(localStorage.getItem('user'));
  }catch(e){
    return null;
  }
}
//正则验证
const pattern = {
  integer: /^\d+$/,
  doubleFix2: /^[0-9]+(\.\d{1,2})?$/,
  price: /^[0-9]+(\.\d{1,2})?$/,
  phone: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
  email: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/,
  idCard: /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/,
  postCode: /^\d{6}$/
}

//File/Blob 转 ArrayBuffer
const File2ArrayBuffer = (file) => {
  return new Promise(resolve => {
    let fr = new FileReader();
    fr.readAsArrayBuffer(file);
    fr.addEventListener("loadend",(e) => {
      let buf = e.target.result;
      resolve(buf);
    },false);
  })
}

// 将base64转换为文件
const dataURLtoFile = (dataurl, filename = 'a') => {
  let arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
}

// 将base64转换为blob
const dataURLtoBlob = dataurl => {
  let arr = dataurl.split(","),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], { type: mime });
}

//file/blob转base64
const fileToBase64 = blob => {
  return new Promise(resolve => {
    let reader = new FileReader();
    reader.readAsDataURL(blob);
    reader.onload = function (evt) {
      resolve(evt.target.result);
    };
  })
}

//转换图片/视频地址
const generateMediaUrl = ({fileId, fileOpenUrl, fileOperQx}) => {
  const auth = fileOperQx === '1';//访问是否需要权限
  if(auth){
    return '/flea/file/download/' + fileId;
  }else{
    const fileHost = process.env.NODE_ENV === 'production' ? 'https://chekuoffice.cn/zero-file-resource/' : 'https://chekuoffice.cn/zero-file-resource/';
    return fileHost + fileOpenUrl;
  }
}

//文件上传的公共方法
const defaultUploadChange = async function(fileObj, cbk, fcbk){
  if(fileObj.status === 'ready'){
    let file = fileObj.raw, fileSize = fileObj.size, fileName = fileObj.name;
    let buffer = await File2ArrayBuffer(file);
    let md5 = this.$MD5(buffer);
    //文件上传
    let formData = new FormData()
    formData.append('businessSysModuleCode', fileObj.businessSysModuleCode || this.businessSysModuleCode);
    formData.append('file', file);
    formData.append('businessSysCode', businessSysCode);
    formData.append('fileSize', fileSize);
    formData.append('md5', md5);
    this.$yAxios({
      url: this.$api.common.upload,
      data: formData,
      loading: true
    }, ({data}) => {
      const param = Object.gain(data, [
        'businessId','businessSysCode','businessSysModuleCode','id:fileId','fileName','fileId:fileOpenUrl'
      ]);
      if(fileObj.businessId) param.businessId = fileObj.businessId;
      param.fileType = file.type;
      param.fileOperQx = '0';
      this.$yAxios({
        url: this.$api.common.saveAttachment,
        data: param,
        loading: true
      }, info => {
        if(cbk){
          cbk(info, file)
        }
      }, e => {
        fcbk && fcbk(e);
      })
    }, e => {
      fcbk && fcbk(e);
    })
  }
}

//Object的部分浅拷贝
Object.gain = function(obj, keys, defaultValue){
  if(typeof keys === 'string') keys = [keys];
  const res = {};
  keys.map(key => {
    let [originKey, newKey = originKey] = key.split(':');
    res[newKey] = (!obj[originKey] && arguments.length === 3) ? defaultValue : obj[originKey];
  });
  return res;
}
export default {
  pattern, File2ArrayBuffer, dataURLtoFile, dataURLtoBlob, fileToBase64, generateMediaUrl, defaultUploadChange
}
